package edu.suda.scratcher.ippgserver.servlet;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.apache.ibatis.session.SqlSession;
import edu.suda.scratcher.ippgserver.mapper.*;
import edu.suda.scratcher.ippgserver.beans.Record;

@WebServlet("/actions/list_records.csv")
public class ListRecords extends Action {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/csv");       
        HttpSession httpSession = request.getSession(true);
        Writer writer = response.getWriter();
        String username = (String)httpSession.getAttribute("username");
        
        SqlSession sqlSession = sqlSessionFactory.openSession();
        RecordMapper mapper = sqlSession.getMapper(RecordMapper.class);
        
        Record records[] = mapper.listRecords(username);
        for (Record record: records) {
            writer.write(record.toString() + "\n");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    
}
